package cn.easyplatform.studio.cmd.biz;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.utils.StringUtil;
import cn.easyplatform.studio.vos.TableFieldVo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class GetTableFieldCmd implements Command<List<TableFieldVo>> {

    private String tableName;

    public GetTableFieldCmd(String tableName) {
        this.tableName = tableName;
    }
    @Override
    public List<TableFieldVo> execute(CommandContext cc) {
        List<Object[]> res = cc.getBizDao().selectList(
                "SELECT table1id,table1name,table1description,field1name,field1type,field1length,field1decimal," +
                        "field1description,field1notnull,field1orderNo FROM sys_table_field_info WHERE " +
                        "table1id='" + tableName + "'");
        List<TableFieldVo> list = new ArrayList<>();
        for (Object[] objs : res) {
            Integer integer = -1;
            if (Strings.isBlank((String)objs[9]) == false && StringUtil.isInteger((String)objs[9]))
                integer = Integer.parseInt((String)objs[9]);
            TableFieldVo fieldVo = new TableFieldVo((String)objs[0], (String)objs[1], (String)objs[2], (String)objs[3],
                    (String)objs[4], (String)objs[5], (String)objs[6], (String)objs[7], (String)objs[8], integer);
            list.add(fieldVo);
        }
        for (int index = 0; index < list.size(); index++) {
            for (int j = 0; j < list.size() - index; j++) {
                if (j + 1 < list.size()) {
                    TableFieldVo fieldVo1 = list.get(j);
                    TableFieldVo fieldVo2 = list.get(j + 1);
                    if (fieldVo1.getFieldOrderNo() > fieldVo2.getFieldOrderNo()) {
                        TableFieldVo vo = (TableFieldVo) fieldVo1.clone();
                        list.set(j, fieldVo2);
                        list.set(j + 1, vo);
                    }
                }
            }
        }
        return list;
    }
}
